const express = require("express");
const multer = require("multer");
const router = express.Router();
const path = require("path");

const {
  generateUniqueId,
  fileUrl,
  host,
} = require("../public/javascripts/index");
const db = require("../db");

router.post("/add", (req, res) => {
  // 执行定义好的登录函数
  const info = req.body;
  // 定义 SQL 语句
  let sql = "insert into selection_business set ?";
  db.query(
    sql,
    {
      businessId: generateUniqueId(),
      businessName: info.businessName,
      warehouseId: info.warehouseId,
      warehouseName: info.warehouseName,
      address: info.address,
      provinceName: info.provinceName,
      provinceCode: info.provinceCode,
      cityName: info.cityName,
      cityCode: info.cityCode,
      districtName: info.districtName,
      districtCode: info.districtCode,
      contacts: info.contacts,
      tel: info.tel,
      url: info.url,
      createdTime: Date.now(),
      remark: info.remark,
    },
    (error, result) => {
      if (error) return res.cc(error);
      // 判断影响行数是否为 1
      if (result.affectedRows !== 1) return res.cc("新增商家失败！");
      return res.cc("新增商家成功", true);
    }
  );
});

router.delete("/delete", (req, res) => {
  const info = req.body;
  //对客户端的数据进行校验
  if (!info.businessId) {
    return res.send({
      success: false,
      message: "编码不能为空",
    });
  }
  // 执行定义好的登录函数
  let sql = "select * from selection_business where businessId=?";
  db.query(sql, [info.businessId], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    if (result.length === 0) {
      return res.cc("未找到该记录!");
    }
    // 定义 SQL 语句
    const sql1 = "delete from selection_business where businessId=?";
    // 调用 db.query() 执行 sql 语句
    db.query(sql1, info.businessId, (error, result) => {
      if (error) return res.cc(error);
      // 判断影响行数是否为 1
      if (result.affectedRows !== 1) return res.cc("删除失败！");
      return res.cc("删除成功", true);
    });
  });
});

router.put("/update", (req, res) => {
  const info = req.body;

  // 对客户端的数据进行校验
  if (!info.businessId) {
    return res.send({
      success: false,
      message: "编码不能为空",
    });
  }

  // 执行定义好的登录函数
  let sql = "SELECT * FROM selection_business WHERE businessId=?";
  db.query(sql, [info.businessId], (error, result) => {
    if (error) {
      return res.cc(error);
    }

    if (result.length === 0) {
      return res.cc("未找到该记录!");
    }

    // 更新库信息
    const updateSQL =
      "UPDATE selection_business SET " +
      "businessName=?, " +
      "warehouseName=?, " +
      "address=?, " +
      "provinceName=?, " +
      "provinceCode=?, " +
      "cityName=?, " +
      "cityCode=?, " +
      "districtName=?, " +
      "districtCode=?, " +
      "contacts=?, " +
      "tel=?, " +
      "url=?, " +
      "remark=? " +
      "WHERE businessId=?";

    const updateValues = [
      info.businessName,
      info.warehouseName,
      info.address,
      info.provinceName,
      info.provinceCode,
      info.cityName,
      info.cityCode,
      info.districtName,
      info.districtCode,
      info.contacts,
      info.tel,
      info.url,
      info.remark,
      info.businessId,
    ];

    db.query(updateSQL, updateValues, (error, result) => {
      if (error) {
        return res.cc(error);
      }

      if (result.affectedRows !== 1) {
        return res.cc("修改失败！");
      }

      return res.cc("修改成功", true);
    });
  });
});

router.post("/list", (req, res) => {
  const {
    page = 1,
    limit = 10,
    warehouseName = "",
    businessName = "",
    contacts = "",
    tel = "",
  } = req.body;
  const offset = (page - 1) * limit;

  // 构建基础查询和参数
  let baseQuery = " FROM selection_business WHERE 1=1";
  let params = [];

  if (warehouseName) {
    baseQuery += " AND warehouseName LIKE ?";
    params.push(`%${warehouseName}%`);
  }
  if (businessName) {
    baseQuery += " AND businessName LIKE ?";
    params.push(`%${businessName}%`);
  }
  if (contacts) {
    baseQuery += " AND contacts LIKE ?";
    params.push(`%${contacts}%`);
  }
  if (tel) {
    baseQuery += " AND tel LIKE ?";
    params.push(`%${tel}%`);
  }

  // 构建 SQL 计数查询语句
  const sqlCount = `SELECT COUNT(*) AS total ${baseQuery}`;

  // 查询总条数
  db.query(sqlCount, params, (error, countResults) => {
    if (error) {
      return res.cc(error);
    }

    const total = countResults[0].total;

    // 构建 SQL 查询语句
    let sql = `SELECT * ${baseQuery} LIMIT ? OFFSET ?`;
    params.push(limit, offset);

    // 执行查询
    db.query(sql, params, (error, results) => {
      if (error) {
        return res.cc(error);
      }
      return res.cc("获取记录成功", true, results, {
        total,
        page,
        limit,
      });
    });
  });
});

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, fileUrl); // 指定 Nginx 服务器的静态文件目录
  },
  filename: function (req, file, cb) {
    const buffer = Buffer.from(file.originalname, "latin1");
    const decodedFileName = buffer.toString("utf8");
    cb(null, decodedFileName);
  },
});
const upload = multer({ storage: storage });

// POST 请求处理上传的文件
router.post("/upload", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.cc("未上传文件");
  }

  // 文件上传成功
  const filePath = path.join(host, req.file.filename); // 文件在 Nginx 服务器上的路径
  const realFilePath = "http://" + filePath.replace(/\\/g, "/");
  return res.cc("文件上传成功", true, realFilePath);
});

module.exports = router;
